﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SELF.Model;
using System.Collections;
using System.Diagnostics;
using System.Threading;
using System.Xml;
using System.IO;

namespace SELF
{
    public partial class frm_Course : DevExpress.XtraEditors.XtraForm
    {
        public frm_Course()
        {
            InitializeComponent();
            this.Activated += new EventHandler(frm_Course_Activated);
        }
        private bool _ontop = true;
        private string _filePlaying;

        public string FilePlaying
        {
            get { return _filePlaying; }
            set { _filePlaying = value; }
        }
        void frm_Course_Activated(object sender, EventArgs e)
        {
            //
            if (GetRoundTime() > 0)
            {
                if (VDOStatus._CountDownInSec >= (GetRoundTime() * 60))
                {
                    this.TopMost = _ontop;
                    //label17.Text = SELF.Model.Leaning.Int2TimeWithSec(VDOStatus._CountDownInSec);
                    label17.Text = String.Format("{0} / {0}", Leaning.Int2TimeWithSec(GetRoundTime() * 60));
                    //throw new NotImplementedException();
                }
                else
                {
                    this.TopMost = _ontop;
                    label17.Text = String.Format("{0} / {1}", Leaning.Int2TimeWithSec(VDOStatus._CountDownInSec), Leaning.Int2TimeWithSec(GetRoundTime() * 60));
                }
            }
            //
            DrawGrid();
            //
        }

        lcmpt.Connection Conn = new lcmpt.Connection();

        #region fields

        private TreeNode tnRoot = new TreeNode();
        private string ticketID;
        DataRow drCurrent;
        private string fileStr;
        private string fileType;
        private string ipAddr;
        private string studentName;
        private int _ServerTime;
        private int _EndTimeWithSec;
        private int _1stAlert;
        private int _2ndAlert;

        private int _1stAlertInSec;
        private int _2ndAlertInSec;

        #endregion

        #region property

        public string TicketID
        {
            get { return ticketID; }
            set { ticketID = value; }
        }

        public string StudentName
        {
            get { return studentName; }
            set { studentName = value; }
        }

        public string IpAddr
        {
            get { return ipAddr; }
            set { ipAddr = value; }
        }

        #endregion

        public string RandomString(int size)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            string ch;
            for (int i = 0; i < size; i++)
            {
                int s = random.Next(0, 1);
                switch (s)
                {
                    case 0: ch = "" + Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                        builder.Append(ch);
                        break;
                    case 1: ch = random.Next(1, 9).ToString();
                        builder.Append(ch);
                        break;
                }
            }
            return builder.ToString().ToUpper();
        }


        System.Windows.Forms.Timer tmRemaining = new System.Windows.Forms.Timer();
        System.Windows.Forms.Timer tmCountDown = new System.Windows.Forms.Timer();

        Thread thProgress;
        WaitDialog.CircleThick proMar;
        private void showProgress()
        {
            proMar = new WaitDialog.CircleThick();
            proMar.TopMost = true;
            proMar.ShowDialog();
        }

        lcmpt.MouseHelper mous = new lcmpt.MouseHelper();
        private void frm_Course_Load(object sender, EventArgs e)
        {
            thProgress = new Thread(new ThreadStart(showProgress));
            thProgress.Start();

            cGobal._LogRound = RandomString(9);
            _ServerTime = Leaning.TimeToValueWithSec(Leaning.GetServerTime());
            _EndTimeWithSec = EndTimeInSec();

            GetRemainTime();


            tmCountDown.Interval = 1000;
            tmCountDown.Tick += new EventHandler(tmCountDown_Tick);
            tmCountDown.Start();


            Image image_bg = Image.FromFile(cGobal.ImagePath.ToString() + cGobal.ThemeID.ToString() + @"\Course\main_course.png");
            this.BackgroundImage = image_bg;
            this.BackgroundImageLayout = ImageLayout.Tile;


            new TouchScrollHelper(gridView1);
            //update ticket use time
            string strUpdUseTime = @"EXECUTE [dbo].[spl_UseTime_Update] '@Ticket'";
            strUpdUseTime = strUpdUseTime.Replace("@Ticket", TicketID);
            Conn.Execute(strUpdUseTime);

            //[sp_Get_TicketDetials]
            string strTicket = @"EXECUTE [sp_Get_TicketDetials] '@Ticket'";
            strTicket = strTicket.Replace("@Ticket", TicketID);

            using (DataSet ds = Conn.Retreive(strTicket))
            {
                DataSet dss = Conn.Retreive(strTicket);
                if (dss != null)
                {
                    string ticket = ds.Tables[0].Rows[0]["TicketID"].ToString();
                    string name = ds.Tables[0].Rows[0]["MemberName"].ToString();
                    Leaning.SetMechineState(Leaning.StateMechine.Logon);
                    lbl17.Text = ticket;
                    lbl18.Text = name;
                }
            }


            //
            //Get alert time
            //
            DataSet ds1stAlert = Conn.Retreive(@"SELECT TOP 1 [Value] FROM [dbo].[DataSetting] WHERE [DataSettingName] = '1ST_ALERT_BEFOR_TIMEOUT'");
            if ((ds1stAlert != null) || ds1stAlert.Tables[0].Rows.Count > 0)
            {
                _1stAlert = Convert.ToInt32(ds1stAlert.Tables[0].Rows[0]["Value"]);
                _1stAlertInSec = _1stAlert * 60;
            }

            DataSet ds2ndAlert = Conn.Retreive(@"SELECT TOP 1 [Value] FROM [dbo].[DataSetting] WHERE [DataSettingName] = '2ND_ALERT_BEFOR_TIMEOUT'");
            if ((ds2ndAlert != null) || ds2ndAlert.Tables[0].Rows.Count > 0)
            {
                _2ndAlert = Convert.ToInt32(ds2ndAlert.Tables[0].Rows[0]["Value"]);
                _2ndAlertInSec = _2ndAlert * 60;
            }

            //int timeRemain = EndTime() - SELF.Model.Leaning.TimeToValue(SELF.Model.Leaning.GetServerTime());
            //timeRemain = timeRemain * 60;
            //this.timeRemainning = timeRemain;
            if (Conn.IsOnline)
            {
                label17.Text = Leaning.Int2TimeWithSec(VDOStatus._CountDownInSec) + " / " + Leaning.Int2TimeWithSec(GetRoundTime() * 60);
            }

            try
            {
                string sqlRight = @"SELECT TOP 1 HIS.* 
                                    FROM Dim_TicketHistory HIS
                                    WHERE TicketID = @TicketID
                                    AND HIS.CourseName = (
	                                    SELECT CourseName 
	                                    FROM Dim_Courses 
	                                    WHERE CourseID = (
		                                    SELECT CourseID 
		                                    FROM Fact_LearningTicket
		                                    WHERE TicketID = @TicketID
		                                    )
	                                    )
                                    ORDER BY HIS.ID DESC";
                sqlRight = sqlRight.Replace("@TicketID", ticketID);
                DataSet ds5 = Conn.Retreive(sqlRight);
                string courseName = ds5.Tables[0].Rows[0]["CourseName"].ToString();
                label23.Text = courseName;
                string lastTime = Convert.ToDateTime(ds5.Tables[0].Rows[0]["BeginTime"]).ToString();
                label22.Text = lastTime;
                label24.Text = Leaning.Int2TimeWithSec(Convert.ToInt32(ds5.Tables[0].Rows[0]["Usage"]));
            }
            catch (Exception ex)
            {
                label23.Text = "--ไม่มีข้อมูล--";
                label22.Text = "--ไม่มีข้อมูล--";
                label24.Text = "--ไม่มีข้อมูล--";
                //Console.WriteLine("Dim_TicketHistory :"+ex.Message);
                //do nothing
            }

            setUsing();
            DrawNode();
            //mapPath(); 
            if (thProgress.IsAlive)
            {
                this.Invoke((MethodInvoker)delegate
                {
                    proMar.Close();
                    thProgress.Abort();
                });
            }
        }

        void tmCountDown_Tick(object sender, EventArgs e)
        {
            VDOStatus._CountDownInSec = VDOStatus._CountDownInSec - 1;
            //
            //check alert time
            //
            if (VDOStatus._CountDownInSec == (_1stAlertInSec))
            {
                CustomDialog.MessageDialog mes = new CustomDialog.MessageDialog("เวลาจองคงเหลือ " + _1stAlert + " นาที", _1stAlertInSec);
                mes.ShowDialog();
            }
            if (VDOStatus._CountDownInSec == (_2ndAlertInSec))
            {
                CustomDialog.MessageDialog mes = new CustomDialog.MessageDialog("เวลาจองคงเหลือ " + _2ndAlert + " นาที", _2ndAlertInSec);
                mes.ShowDialog();
            }

            #region time out
            if (VDOStatus._CountDownInSec < 1)
            {
                try
                {
                    Leaning.SetMechineState(Leaning.StateMechine.Open);
                    setTicketUsed();
                    //unMapPath();
                    tmCountDown.Stop();

                    this.Invoke((MethodInvoker)delegate
                    {
                        SetCloseProc();
                    });
                    thPlayer.Abort();
                    this.Close();
                }
                catch
                {

                }
            }
            #endregion

            if (((VDOStatus._CountDownInSec % 60) == 0) && VDOStatus.PlayingState)
            {
                SetHistoryEnd();
                CalcUsageTime();
            }
        }

        void SetCloseProc()
        {
            try
            {
                proc.Kill();
            }
            catch { }
        }

        void tmRemaining_Tick(object sender, EventArgs e)
        {
            
            //throw new NotImplementedException();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            e.Node.Expand();
            DrawGrid(); 
        }

        private void DrawGrid()
        {
            string strLiveCheck = @"SELECT LearningType FROM [dbo].[Fact_LearningTicket] WHERE TicketID = '@Ticket'";
            strLiveCheck = strLiveCheck.Replace("@Ticket", TicketID);
            DataSet dsLive = Conn.Retreive(strLiveCheck);
            //ClearLabelValue();
            //string pNode = e.Node.Parent.Text;
            //string nSelf = e.Node.Text;
            DataSet ds;
            if (dsLive.Tables[0].Rows[0]["LearningType"].ToString() == "Live")
            {
                ds = Conn.Retreive("EXECUTE [dbo].[sp_Get_LiveCoursesDetials] '" + TicketID + "'");
            }
            else
            {
                ds = Conn.Retreive("EXECUTE [dbo].[sp_Get_CoursesDetials] '" + TicketID + "'");
            }
            //DataSet ds = RunQuery("");
            //string qSql = "EXECUTE [dbo].[sp_Get_CoursesFromName] '" + pNode + "','" + nSelf + "','" + TicketID + "'";
            //DataSet ds = Conn.Retreive(qSql, Conn.con);
            if (ds == null)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("There are no course avaliable for this ticket, Please contact administrators", "No course avaliable");
            }
            else
            {
                CoreEngine.Util.DevExpressDataGridUtil.Fill(gridControl1, ds);
                CoreEngine.Util.DevExpressDataGridUtil _config = new CoreEngine.Util.DevExpressDataGridUtil();
                _config.SetParameterColumn("TicketID", "TicketID", false, 100, DevExpress.Utils.HorzAlignment.Default);
                _config.SetParameterColumn("MemberName", "MemberName", false, 100, DevExpress.Utils.HorzAlignment.Default);
                _config.SetParameterColumn("TypeCourse", "ประเภทคอร์ส", true, 100, DevExpress.Utils.HorzAlignment.Center);
                _config.SetParameterColumn("CourseName", "ชื่อคอร์ส", true, 100, DevExpress.Utils.HorzAlignment.Center);
                _config.SetParameterColumn("LectureName", "ครั้งที่", true, 100, DevExpress.Utils.HorzAlignment.Center);
                _config.SetParameterColumn("Description", "รายละเอียด", true, 100, DevExpress.Utils.HorzAlignment.Center);
                _config.SetParameterColumn("Length", "เวลาเรียนทั้งหมด", true, 100, DevExpress.Utils.HorzAlignment.Center);
                _config.SetParameterColumn("UseTime", "เวลาที่ใช้", true, 100, DevExpress.Utils.HorzAlignment.Center);
                _config.SetParameterColumn("SaleDate", "SaleDate", false, 100, DevExpress.Utils.HorzAlignment.Center);
                _config.SetParameterColumn("EndTimeCourseBuy", "เรียนได้ถึง", true, 100, DevExpress.Utils.HorzAlignment.Center);
                _config.SetParameterColumn("VdoName", "VdoName", false, 100, DevExpress.Utils.HorzAlignment.Default);
                _config.SetParameterColumn("TypeFile", "TypeFile", false, 100, DevExpress.Utils.HorzAlignment.Default);
                _config.SetParameterColumn("BalanceTime", "BalanceTime", false, 100, DevExpress.Utils.HorzAlignment.Center);
                _config.SetParameterColumn("AllTime", "AllTime", false, 100, DevExpress.Utils.HorzAlignment.Center);
                _config.SetParameterColumnFormat("EndTimeCourseBuy", CoreEngine.Util.DevExpressDataGridUtil.FormatType.DateTime, "dd/mm/yyyy");
                _config.GridViewRanderConfig(gridView1);
                _config.GridViewRanderDataFormat(gridControl1);
                CoreEngine.Util.DevExpressDataGridUtil.BestFitAllColumn(gridView1);

                cGobal.TicketBalance = ds.Tables[0].Rows[0]["BalanceTime"].ToString();
                cGobal.TicketTime = ds.Tables[0].Rows[0]["AllTime"].ToString();

                label18.Text = cGobal.TicketBalance + " / " + cGobal.TicketTime;
                //LectureID
            }
        }

        private void plExit_Click(object sender, EventArgs e)
        {
            Dialog_Close cls = new Dialog_Close();
            cls.ShowDialog();
            if (cls.DialogResult == DialogResult.Yes)
            {
                tmCountDown.Stop();
                //unMapPath();
                Leaning.SetMechineState(Leaning.StateMechine.Open);
                setTicketUsed();
                this.Close();
                this.Dispose();
            }
        }

        Process proc = new Process();
        Thread thPlayer;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void plEnterCourse_Click(object sender, EventArgs e)
        {
            if (fileStr == "")
            {
                drCurrent = gridView1.GetDataRow(0);
                setLabelValue(drCurrent);
            }
            try
            {
                if (fileStr != "" && fileStr != null)
                {
                    Dialog_in enter = new Dialog_in();
                    enter.ShowDialog();
                    if (enter.DialogResult == DialogResult.Yes)
                    {

                        //
                        //start loging and set admission time to booking
                        string sqlAddHistory = @"INSERT INTO [dbo].[Dim_TicketHistory]
               ([LogRound],[TicketID],[CourseName],[LectureName],[Description],[BeginTime])
                VALUES('@logRound','@TicketID','@Course','@Lecture','@Description',GETDATE())";

                        sqlAddHistory = sqlAddHistory.Replace("@logRound", cGobal._LogRound);
                        sqlAddHistory = sqlAddHistory.Replace("@TicketID", ticketID);
                        sqlAddHistory = sqlAddHistory.Replace("@Course", lbl2.Text);
                        sqlAddHistory = sqlAddHistory.Replace("@Lecture", lbl3.Text);
                        sqlAddHistory = sqlAddHistory.Replace("@Description", lbl4.Text);
                        Conn.Execute(sqlAddHistory);
                        //end code
                        //

                        //set state 
                        Leaning.SetMechineState(Leaning.StateMechine.Play);

                        int vdoCountdown = VDOStatus._CountDownInSec;

                        string testFile = @"Z:\1241\D4FF7W038265A53.wmv" + "&" + vdoCountdown.ToString(); ;
                        /////////////////////////////////////////////////////////////////////////////////////////////

                        //add link string
                        //move to function
                        GetPlayURL();

                        ///////////////////////////////////////////////////////////////////////////////////////////////

                        thPlayer = new Thread(new ParameterizedThreadStart(StartPlayer));
                        thPlayer.Start(FilePlaying);
                        Thread.Sleep(10000);

                        //SELF.Controls.frm_player player = new SELF.Controls.frm_player();
                        //player.FileName = fileStr;
                        //player.FileType = fileType;
                        //player.LogOnTicket = ticketID;
                        //player.ShowDialog();
                    }
                }
                else
                {
                    MessageBoxCustom mes = new MessageBoxCustom("กรุณาเลือกม้วนที่ต้องการเรียน", 0);
                    mes.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                MessageBoxCustom mes = new MessageBoxCustom(ex.Message, 0);
                mes.ShowDialog();
            }
        }

        private void GetPlayURL()
        {
            const string sectionName = "ShareLink";
            string conf = Application.StartupPath + "\\Configurations.xml";
            FilePlaying = "";

            DataTable dtLink = new DataTable();
            dtLink = lcmpt.StandardDoc.ConvertToDataTable(conf, sectionName);

            bool hasFile = false;
            try
            {
                for (int i = 0; i < dtLink.Rows.Count; i++)
                {
                    string point = dtLink.Rows[i]["MapPoint"].ToString();
                    string tmp = point.Replace(":", "");

                    if (IsDriveMapped(tmp))
                    {
                        string fileChk = String.Format("{0}\\Storage\\{1}\\{2}{3}", point.ToUpper(), cGobal.GetCourseID(fileStr), fileStr, fileType);
                        if (File.Exists(fileChk))
                        {
                            FilePlaying = String.Format("{0}\\Storage\\{1}\\{2}{3}&{4}", point.ToUpper(), cGobal.GetCourseID(fileStr), fileStr, fileType, VDOStatus._CountDownInSec);
                            hasFile = true;
                            break;
                        }
                        fileChk = String.Format("{0}\\{1}\\{2}{3}", point.ToUpper(), cGobal.GetCourseID(fileStr), fileStr, fileType);
                        if (File.Exists(fileChk))
                        {
                            FilePlaying = String.Format("{0}\\{1}\\{2}{3}&{4}", point.ToUpper(), cGobal.GetCourseID(fileStr), fileStr, fileType, VDOStatus._CountDownInSec);
                            hasFile = true;
                            break;
                        }
                    }
                }
                if (FilePlaying == "")
                {
                    throw new Exception("ไม่พบแฟ้มที่ต้องการ");
                }

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            dtLink.Dispose();
        }

        private void StartPlayer(object fname)
        {
            try
            {
                Process[] prs = Process.GetProcesses();
                foreach (Process pr in prs)
                {
                    Console.WriteLine(pr.ProcessName);
                    if (pr.ProcessName == "WinPlayer")
                    {
                        pr.Kill();
                    }
                }
            }
            catch { }


            proc.StartInfo.FileName = Application.StartupPath + "\\WinPlayer\\WinPlayer.exe";
            string name = fname.ToString();
            proc.StartInfo.Arguments = name;
            proc.Start();
            proc.WaitForExit();
            //this.Invoke((MethodInvoker)delegate
            //{
            //    SetHistoryEnd();
            //});
            SetHistoryEnd();
            CalcUsageTime();
            Leaning.SetMechineState(Leaning.StateMechine.Logon);

        }

        private void SetHistoryEnd()
        {
            try
            {
                string sqlUpdHis = @"UPDATE [dbo].[Dim_TicketHistory] 
                                  SET [EndTime] = GETDATE()
                                  WHERE [TicketID] = '@TicketID'
                                  AND [ID] = (SELECT TOP 1 ID FROM [dbo].[Dim_TicketHistory] WHERE [TicketID] = '@TicketID' ORDER BY ID DESC)";
                sqlUpdHis = sqlUpdHis.Replace("@TicketID", ticketID);
                Conn.Execute(sqlUpdHis);
            }
            catch { }
        }

        private void CalcUsageTime()
        {
            string sqlCalcUsage = @" UPDATE [dbo].[Dim_TicketHistory] 
                                     SET [Usage] = (SELECT DATEDIFF(SECOND,A.BeginTime,A.EndTime)
				                                    FROM [dbo].[Dim_TicketHistory] as A
				                                    WHERE ID = (SELECT TOP 1 ID FROM [dbo].[Dim_TicketHistory] WHERE [TicketID] = '@TicketID' ORDER BY ID DESC))
                                      WHERE [TicketID] = '@TicketID'
                                      AND [ID] = (SELECT TOP 1 ID FROM [dbo].[Dim_TicketHistory] WHERE [TicketID] = '@TicketID' ORDER BY ID DESC)";
            sqlCalcUsage = sqlCalcUsage.Replace("@TicketID", ticketID);
            Conn.Execute(sqlCalcUsage);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            drCurrent = gridView1.GetDataRow(e.RowHandle);
            setLabelValue(drCurrent);
        }

        private void plHistory_Click(object sender, EventArgs e)
        {
            Leaning.SetMechineState(Leaning.StateMechine.Logon);
            SELF.Controls.frm_CourseHistory his = new SELF.Controls.frm_CourseHistory();
            his.TicketID = Common.Member.TicketID;
            his.ShowDialog();

            if (his.DialogResult == DialogResult.Ignore)
            {
                tmCountDown.Stop();
                //unMapPath();
                Leaning.SetMechineState(Leaning.StateMechine.Open);
                setTicketUsed();
                this.Close();
                this.Dispose();
            }
        }
        WaitDialog.CircleThick circleProg; 
        Thread chromOpener;
        private void Reserv_Click(object sender, EventArgs e)
        {
            if (Conn.IsOnline)
            {
                try
                {
                    chromOpener = new Thread(new ThreadStart(SatrtChrome));
                    chromOpener.Start();
                    circleProg.ShowDialog();
                }
                catch { }
            }
            else
            {
                CustomDialog.MessageDialog mes = new CustomDialog.MessageDialog("ไม่สามารถจองได้ในขณะนี้ กรุณาติดต่อเจ้าหน้าที่",20);
                mes.ShowDialog();
            }
        }

        private void SatrtChrome()
        {
            Process[] prs = Process.GetProcesses();
            foreach (Process pr in prs)
            {
                Console.WriteLine(pr.ProcessName);
                if (pr.ProcessName == "chrome")
                {
                    pr.Kill();
                }
            }
            this.TopMost = false;
            proc.StartInfo.FileName = Config.Configurations.ChromePath;
            string name = " --kiosk " + Config.Configurations.BookingURL;
            proc.StartInfo.Arguments = name;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
            proc.Start();
            //proc.WaitForExit();
            Thread.Sleep(15000);
            this.Invoke((MethodInvoker)delegate
            {
                circleProg.Close();
                chromOpener.Abort();
            });
        }

        private int StartTime()
        {
            try
            {
                int endTime = 0;
                string sqlMinEnd = @"SELECT MinStart
                              FROM [dbo].Detail_Time
                              WHERE TimeId = (SELECT MAX(TimeId) 
                              FROM [dbo].[Booking]
                              WHERE [ROUND] = @dRound)";
                sqlMinEnd = sqlMinEnd.Replace("@dRound", SELF.VDOStatus.RoundLogin);
                DataSet ds = Conn.Retreive(sqlMinEnd);
                if (ds != null && (ds.Tables[0].Rows.Count != 0))
                {
                    VDOStatus._startTime = ds.Tables[0].Rows[0][0].ToString();
                    endTime = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                }
                return endTime;
            }
            catch
            {
                return 0;
            }
        }

        private int EndTime()
        {
            try
            {
                int endTime = 0;
                string sqlMinEnd = @"SELECT MinEnd
                              FROM [dbo].Detail_Time
                              WHERE TimeId = (SELECT MAX(TimeId) 
                              FROM [dbo].[Booking]
                              WHERE [ROUND] = @dRound)";
                sqlMinEnd = sqlMinEnd.Replace("@dRound", SELF.VDOStatus.RoundLogin);
                DataSet ds = Conn.Retreive(sqlMinEnd);
                if (ds != null && (ds.Tables[0].Rows.Count != 0))
                {
                    VDOStatus._endTime = ds.Tables[0].Rows[0][0].ToString();
                    endTime = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                    //MessageBox.Show("End time is : "+endTime);
                }
                return endTime;
            }
            catch
            {
                return 0;
            }
        }

        private int EndTimeInSec()
        {
            try
            {
                int endTime = 0;
                string sqlMinEnd = @"SELECT MinEnd
                              FROM [dbo].Detail_Time
                              WHERE TimeId = (SELECT MAX(TimeId) 
                              FROM [dbo].[Booking]
                              WHERE [ROUND] = @dRound)";
                sqlMinEnd = sqlMinEnd.Replace("@dRound", SELF.VDOStatus.RoundLogin);
                DataSet ds = Conn.Retreive(sqlMinEnd);
                if (ds != null && (ds.Tables[0].Rows.Count != 0))
                {
                    VDOStatus._endTime = ds.Tables[0].Rows[0][0].ToString();
                    endTime = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                    endTime = endTime * 60;
                }
                return endTime;
            }
            catch
            {
                return 0;
            }
        }   

        public static bool IsDriveMapped(string sDriveLetter)
        {
            sDriveLetter = sDriveLetter.ToUpper();
            string[] DriveList = Environment.GetLogicalDrives();
            for (int i = 0; i < DriveList.Length; i++)
            {
                if (sDriveLetter + ":\\" == DriveList[i].ToString())
                {
                    return true;
                }
            }
            return false;
        }

        private void setUsing()
        {
            try
            {
                string sql = @"UPDATE [dbo].[Dim_Station]
                        SET [TicketID] = '@TicketID', [StudentName]='@StudentName'
                        WHERE [IPAddress]='@IPAddr'";
                sql = sql.Replace("@TicketID", TicketID);
                sql = sql.Replace("@StudentName", StudentName);
                sql = sql.Replace("@IPAddr", IpAddr);
                Conn.Execute(sql);

                sql = @" UPDATE [dbo].[Fact_LearningTicket]
                        SET [StateTicket]='Using'
                        WHERE [TicketID] = '@TicketID'";
                sql = sql.Replace("@TicketID", TicketID);
                Conn.Execute(sql);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void setTicketUsed()
        {
            try
            {
                string sql = @" UPDATE [dbo].[Fact_LearningTicket]
                        SET [StateTicket]='Use'
                        WHERE [TicketID] = '@TicketID'";
                sql = sql.Replace("@TicketID", TicketID);
                Conn.Execute(sql);

                sql = @"UPDATE [dbo].[Dim_Station]
                        SET [TicketID] = '', [StudentName]=''
                        WHERE [IPAddress]='@IPAddr'";
                sql = sql.Replace("@IPAddr", IpAddr);
                Conn.Execute(sql);
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
        }

        private void DrawNode()
        {
            string sql = @"SELECT b.TypeCourse
                  FROM [dbo].[Fact_LearningTicket] as a,
                  [dbo].[Dim_Courses] as b
                  where TicketID = '@TicketID'
                  and a.CourseID = b.CourseID";
            sql = sql.Replace("@TicketID", TicketID);
            DataSet dsRoot = Conn.Retreive(sql);
            treeView1.Nodes.Clear();
            tnRoot.Text = "All Courses Available";
            tnRoot.Name = "rootNode";
            tnRoot.Expand();
            treeView1.Nodes.Add(tnRoot);
            foreach (DataRow dr in dsRoot.Tables[0].Rows)
            {
                TreeNode tnParent = new TreeNode();
                tnParent.Text = dr[0].ToString().Trim();
                tnParent.Name = dr[0].ToString().Trim();
                tnParent.Expand();
                tnRoot.Nodes.Add(tnParent);
                DrawChildNode(tnParent, tnParent.Name);
            }
            treeView1.ExpandAll();

        }

        private void DrawChildNode(TreeNode parent, string ParentId)
        {
            string sql = @"SELECT b.CourseName
                      FROM [dbo].[Fact_LearningTicket] as a,
                      [dbo].[Dim_Courses] as b
                      where TicketID = '@TicketID'
                      and a.CourseID = b.CourseID";
            sql = sql.Replace("@TicketID", TicketID);
            DataSet dsChild = Conn.Retreive(sql);
            foreach (DataRow dr in dsChild.Tables[0].Rows)
            {
                TreeNode child = new TreeNode();
                child.Text = dr[0].ToString().Trim();
                child.Name = dr[0].ToString().Trim();
                child.Collapse();
                parent.Nodes.Add(child);
            }
        }

        private void setLabelValue(DataRow row)
        {
            string a = row.ToString();
            string studentName = row["MemberName"].ToString();
            lbl1.Text = row["TypeCourse"].ToString();
            lbl2.Text = row["CourseName"].ToString();
            lbl3.Text = row["LectureName"].ToString();
            lbl4.Text = row["Description"].ToString();
            lbl5.Text = row["Length"].ToString();//เวลาทั้งหมด
            lbl6.Text = row["UseTime"].ToString();//เวลาที่ใช้
            //lbl6.Text = SELF.Model.Leaning.Int2TimeWithSec(GetRoundTime() * 60).ToString();
            lbl7.Text = row["SaleDate"].ToString();//วันที่ซื้อ
            lbl8.Text = row["EndTimeCourseBuy"].ToString();//เรียนได้ถึง
            fileStr = row["VdoName"].ToString();
            fileType = row["TypeFile"].ToString();

        }

        private void ClearLabelValue()
        {
            //lbl1.Text = "";
            //lbl2.Text = "";
            //lbl3.Text = "";
            //lbl4.Text = "";
            //lbl5.Text = "";
            //lbl6.Text = "";
            //lbl7.Text = "";
            //lbl8.Text = "";
        }

        private int GetRoundTime()
        {
            try
            {
                string sqlCaltime = @"SELECT ((MAX(TimeId)-MIN(TimeId))+1)*30 FROM Booking WHERE [ROUND] = '@Round'";
                sqlCaltime = sqlCaltime.Replace("@Round", VDOStatus.RoundLogin);
                DataSet ds = Conn.Retreive(sqlCaltime);
                return Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            }
            catch { return -1;}
        }

        private void GetRemainTime()
        {
            int secEndTime = _EndTimeWithSec;
            int secServerTie = _ServerTime;
            int timeRemain = secEndTime - secServerTie;

            VDOStatus._CountDownInSec = timeRemain;
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void label3_MouseHover(object sender, EventArgs e)
        {
            if (!Conn.IsOnline)
            {
                mous.DisableMouseClicks();
            }
        }

        private void label3_MouseLeave(object sender, EventArgs e)
        {
            if (!Conn.IsOnline)
            {
                mous.EnableMouseClicks();
            }
        }

    }
}